package com.masonluo.mlonlinejudge.controller;

import com.masonluo.mlonlinejudge.mapper.BookMapper;
import com.masonluo.mlonlinejudge.mapper.IndexMapper;
import com.masonluo.mlonlinejudge.model.bo.BookBo;
import com.masonluo.mlonlinejudge.model.param.BookParam;
import com.masonluo.mlonlinejudge.model.param.EditBookParam;
import com.masonluo.mlonlinejudge.model.vo.BookVo;
import com.masonluo.mlonlinejudge.model.vo.IndexVo;
import com.masonluo.mlonlinejudge.result.Result;
import com.masonluo.mlonlinejudge.service.BookService;
import com.masonluo.mlonlinejudge.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author masonluo
 * @date 2021/2/10 4:53 下午
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private IndexService indexService;

    @Autowired
    private IndexMapper indexMapper;

    @GetMapping
    public Result<List<BookBo>> listBook() {
        List<BookBo> books = bookService.findList();
        return Result.ok(books);
    }

    @GetMapping("/{bookId}/index")
    public Result<List<IndexVo>> listByBookId(@PathVariable("bookId") Integer bookId) {
        return Result.ok(indexMapper.boToVo(indexService.listByBookId(bookId, true)));
    }

    @PostMapping
    public Result<BookBo> add(@RequestBody @Valid BookParam bookParam) {
        BookBo bo = bookService.createBook(bookMapper.paramToCreateDto(bookParam));
        return Result.created(bo);
    }

    @PatchMapping
    public Result<BookBo> update(@RequestBody @Valid EditBookParam editBookParam) {
        BookBo bo = bookService.update(editBookParam);
        return Result.ok(bo);
    }

    @SuppressWarnings("rawtypes")
    @DeleteMapping("/{book_id}")
    public Result delete(@PathVariable("book_id") Integer bookId) {
        bookService.delete(bookId);
        return Result.ok();
    }
}
